package org.xiyu.yee.eggpreview.mixin;

import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.xiyu.yee.eggpreview.client.SpawnEggPreviewRenderer;

import static net.minecraft.world.item.ItemDisplayContext.*;

/**
 * 拦截物品在手中/世界中（层级为固定静态展示）渲染，将刷怪蛋替换为实体 3D 模型的缩略形式。
 * 使用 HEAD 注入并在成功时取消后续原版渲染。
 */
@Mixin(ItemRenderer.class)
public abstract class MixinItemRenderer {

    @Inject(
            method = "render",
            at = @At("HEAD"),
            cancellable = true
    )
    private void eggpreview$renderStatic(
            ItemStack pItemStack, ItemDisplayContext pDisplayContext, boolean pLeftHand, PoseStack pPoseStack, MultiBufferSource pBufferSource, int pCombinedLight, int pCombinedOverlay, BakedModel pModel, CallbackInfo ci) {

        if (pItemStack == null || !SpawnEggPreviewRenderer.canRender(pItemStack)) return;

        // 只处理几个需要的场景：GUI、手持、掉落展示
        switch (pDisplayContext) {
            case GUI,
                 FIRST_PERSON_LEFT_HAND, FIRST_PERSON_RIGHT_HAND,
                 THIRD_PERSON_LEFT_HAND, THIRD_PERSON_RIGHT_HAND,
                 GROUND -> {
                MultiBufferSource.BufferSource buffer = Minecraft.getInstance().renderBuffers().bufferSource();
                boolean ok = SpawnEggPreviewRenderer.renderPreviewItem(pPoseStack, 0, 0, pItemStack, buffer, 0x00F000F0);
                if (ok) {
                    buffer.endBatch();
                    ci.cancel();
                }
            }
            default -> {} // 其它场景保留原版（比如 item frame / fixed）
        }
    }
}
